package com.v1.video.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.iss.view.common.ToastAlone;
import com.iss.view.pulltorefresh.PullToRefreshBase;
import com.iss.view.pulltorefresh.PullToRefreshBase.OnRefreshListener2;
import com.iss.view.pulltorefresh.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.umeng.analytics.MobclickAgent;
import com.utovr.gson.Gson;
import com.v1.video.AppContext;
import com.v1.video.Constant;
import com.v1.video.R;
import com.v1.video.adapter.ThemeAllAdapter;
import com.v1.video.db.dao.MyThemeTB;
import com.v1.video.db.dao.ThemeTB;
import com.v1.video.db.service.ThemeMyThemeDB;
import com.v1.video.domain.LoginInfo;
import com.v1.video.domain.ThemeAllThemeEntity;
import com.v1.video.httpApi.V1VideoHttpApi;
import com.v1.video.httpmanager.RequestManager;
import com.v1.video.httpmanager.RequestManager.OnResponseListener;
import com.v1.video.pay.MD5;
import com.v1.video.util.Helper;
import com.v1.video.util.Logger;
import com.v1.video.util.Utils;

import java.util.ArrayList;
import java.util.List;
/**
 * 主题：全部主题
 * @author fengtao
 *
 */
public class FragmentThemeAllTheme extends V1BaseFragment implements
		IRefresh {
	private final String TAG = "FragmentThemeAllTheme";
	private LayoutInflater mInflater;
	private View mRootView;
	private PullToRefreshListView refreshListView = null;
	private ListView listview = null;
	private ThemeAllAdapter adapter = null;
	private List<ThemeTB> listVideo = new ArrayList<ThemeTB>();
    private LinearLayout layoutHasData = null;
    private LinearLayout layoutNoDataToUpdata = null;
    private RelativeLayout layoutNoData = null;
    
    private final int STATE_REFRESH = 0X0001;//下拉刷新
    private final int STATE_GO_SELECTION = 0X0002;//精选
    private TextView txtToLoginOrSelection = null;
    boolean isAskingServer = false;
    View viewEmpty = null;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		mRootView = mInflater.inflate(R.layout.fragment_theme_alltheme,
				container, false);
		initView();
		initData();
		setListener();
		
		return mRootView;
	}
	
	@Override
	public void onResume() {
		super.onResume();
		MobclickAgent.onPageStart("主题-全部主题");
		Logger.i(TAG, "全部主题onresume执行了");
		
	}	

	@Override
	public void refresh(Object tag) {
		// TODO Auto-generated method stub
		super.refresh(tag);
		viewOfNoLogin();
	}

	private void viewOfNoLogin() {
//		if(!LoginInfo.getInstance().isLogin()){
//			layoutNoData.setVisibility(View.VISIBLE);
//			refreshListView.setVisibility(View.GONE);
//			txtToLoginOrSelection.setText(getResources().getString(R.string.tips_title_subscribe_my_no_login));
//			return;
//		}else{
			refreshListView.setVisibility(View.VISIBLE);
			layoutNoData.setVisibility(View.GONE);
			adapter = null;
			refreshPullDown(true);
//		}
	}

	@Override
	public void onPause() {
		super.onPause();
//		MobclickAgent.onPageEnd("订阅");
		MobclickAgent.onPageEnd("主题-全部主题");
//		clickStatistics(Constant.SUBSCRIBE_MY_ID);
	}

	public Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch(msg.what){
			case STATE_REFRESH:
				Logger.i(TAG, "handleMessage执行了");
				if(refreshListView != null){
					refreshListView.onRefreshComplete();
				}
//				if(!LoginInfo.getInstance().isLogin()){
//					gotoLogin();
//				}
				break;
			}
		}
		
	};
	
	private void initView() {
		refreshListView = (PullToRefreshListView)mRootView.findViewById(R.id.fragment_subscribe_listview);
		listview = refreshListView.getRefreshableView();
		
		layoutHasData = (LinearLayout)mRootView.findViewById(R.id.fragment_subscribe_updata);
		layoutNoDataToUpdata = (LinearLayout)mRootView.findViewById(R.id.fragment_subscribe_noupdata);
		layoutNoData = (RelativeLayout)mRootView.findViewById(R.id.fragment_theme_all_nodata);
		txtToLoginOrSelection = (TextView)mRootView.findViewById(R.id.fragment_subscribe_my_nodata_txt);
		viewEmpty = View.inflate(getActivity().getApplicationContext(),R.layout.fragment_no_content, null);
	}

	private void initData() {
//		refreshPullDown(false);
		viewOfNoLogin();
	}
	
	public void updata(){
		if(listVideo != null && listVideo.size() > 0){
			for(int j = 0; j < listVideo.size();j++){
				listVideo.get(j).setStatus("0");
			}
			if (ThemeMyThemeDB.getInstance().getAllMyThemeData() != null
					&& ThemeMyThemeDB.getInstance().getAllMyThemeData().size() > 0) {
				List<MyThemeTB> listVideoTheme  = ThemeMyThemeDB.getInstance().getAllMyThemeData();
				
				for(int i = 0; i < listVideoTheme.size();i++){
					MyThemeTB mydata = listVideoTheme.get(i);
					for(int j = 0; j < listVideo.size();j++){
						ThemeTB themeData = listVideo.get(j);
						if(themeData.getThemeID().equals(mydata.getThemeID())){
							listVideo.get(j).setStatus("1");
						}
					}
				}
			}
		}
	}
	
	public void updataRefresh(){
		if(listVideo != null && listVideo.size() > 0){
			for(int j = 0; j < listVideo.size();j++){
				listVideo.get(j).setStatus("0");
			}
			if (ThemeMyThemeDB.getInstance().getAllMyThemeData() != null
					&& ThemeMyThemeDB.getInstance().getAllMyThemeData().size() > 0) {
				List<MyThemeTB> listVideoTheme  = ThemeMyThemeDB.getInstance().getAllMyThemeData();
				
				for(int i = 0; i < listVideoTheme.size();i++){
					MyThemeTB mydata = listVideoTheme.get(i);
					for(int j = 0; j < listVideo.size();j++){
						ThemeTB themeData = listVideo.get(j);
						if(themeData.getThemeID().equals(mydata.getThemeID())){
							listVideo.get(j).setStatus("1");
						}
					}
				}
				
			}
			if(adapter != null){
				adapter.notifyDataSetChanged();
			}
		}
	}
	
	/**加载数据*/
	private void refreshPullDown(Boolean isUpdata){
//		if(!LoginInfo.getInstance().isLogin()){
//			return;
//		}else{
//			layoutNoData.setVisibility(View.GONE);
//		}
		String key = "";
		key = MD5.getMessageDigest(V1VideoHttpApi.GET_THEME_ALL_THEME());
		if(!Helper.checkConnection(getActivity())){
			AppContext context = (AppContext) getActivity().getApplicationContext();
//			key = MD5.getMessageDigest(Constant.GET_SUBSCRIBE_MY_1+LoginInfo.getInstance().getUserId()+Constant.GET_SUBSCRIBE_MY_2);
			if(context.getMemeryCache().isExist(key)){
				//若有缓存，则读缓存，显示数据；缓存读取到listVideo
				Logger.i(TAG, "有缓存111111111");
				getDataFromCache(key);
				updata();
				if(adapter != null){					
					adapter.updata(listVideo);		
					adapter.notifyDataSetChanged();
				}else{
					adapter = new ThemeAllAdapter(getActivity(), listVideo);
					listview.setAdapter(adapter);
				}
			}else{
				Logger.i(TAG, "无缓存11111111");
				View view = listview.getEmptyView();
				if(view == null){
					listview.setEmptyView(viewEmpty);
				}
			}
			//若无缓存，则不显示数据；
			if(refreshListView != null){
				refreshListView.onRefreshComplete();
			}
		}else{
			if(isUpdata){//下拉刷新直接从服务器读取数据；
				getDataFromServer();
				return;
			}else{
				if(Constant.isUploadOfSubscribeMy){
					//读缓存
					Logger.i(TAG, "非第一次进，读缓存111111111");
					getDataFromCache(key);
					updata();
					if(adapter != null){
//						adapter.updata(listVideo);		
//						adapter.notifyDataSetChanged();
						listview.setAdapter(adapter);
					}else{
						adapter = new ThemeAllAdapter(getActivity(), listVideo);
						listview.setAdapter(adapter);
					}
				}else{
					Logger.i(TAG, "第一次进，读服务器111111111");
					getDataFromServer();
				}
			}
		}		
	}
	
	private void getDataFromServer(){
		String url = V1VideoHttpApi.GET_THEME_ALL_THEME();
		//http://static.app.m.v1.cn/www/mod/mob/ctl/theme/act/gettotallist/p/5/pcode/010110000/version/4.3.mindex.html
		Logger.i(TAG, "全部主题的url="+url);
		RequestManager.getInstance().getRequest(this.getActivity(), url, null, ThemeAllThemeEntity.class, 0, "FragmentThemeAllTheme", new OnResponseListener(){

			@Override
			public void onSuccess(Object object, int code, String message,String key) {
				// TODO Auto-generated method stub
				Logger.i(TAG, "onSuccess.object="+object.toString());
				if(refreshListView != null){
					Logger.i(TAG, "refreshListView.onRefreshComplete()");
					refreshListView.onRefreshComplete();
				}
				isAskingServer = false;
//				key = MD5.getMessageDigest(Constant.GET_SUBSCRIBE_MY_1+Constant.GET_SUBSCRIBE_MY_2);
				if(object != null){
					boolean isSame = true;//新数据和旧数据是否一样；
					ThemeAllThemeEntity themeAllData = (ThemeAllThemeEntity)object;
					AppContext context = (AppContext) getActivity().getApplicationContext();					
					com.v1.video.domain.BaseEntity.Header header = themeAllData.getHeader();
					if(header.getStatus().equals("2")){
						layoutNoData.setVisibility(View.VISIBLE);
						txtToLoginOrSelection.setText(getResources().getString(R.string.tips_title_subscribe_my_no_updata_tuijian));
						refreshListView.setVisibility(View.GONE);
						return;
					}else{
						refreshListView.setVisibility(View.VISIBLE);
						layoutNoData.setVisibility(View.GONE);
					}
					isSame = judgeOldAndrNewData(key, context, header);
					
					//!isSame若不一样，则 替换存储，替换显示，提示有更新//获取数据后 ，若本地不存在，则直接存储，直接显示，
					if(themeAllData.getBody() != null){
						if(themeAllData.getBody().getData() != null && themeAllData.getBody().getData().size() > 0){
							
							if(!isSame || !context.getMemeryCache().isExist(key)){
								if(header != null && header.getMarkid() != null){
									context.getMemeryCache().putDB(key, header.getMarkid());
									saveInfoToFile(themeAllData.getBody().getData(),key);
								}
								//提示有数据更新
								toastUpdata();
							}
							if(listVideo != null){
								listVideo.clear();
								listVideo.addAll(themeAllData.getBody().getData());
							}
							updata();
							if(adapter != null){
								if(!isSame){
									adapter.updata(listVideo);
									adapter.notifyDataSetChanged();
//									listview.setAdapter(adapter);
								}
//								else{
////									listview.setAdapter(adapter);
//								}
							}else{
								adapter = new ThemeAllAdapter(getActivity(), listVideo);
								listview.setAdapter(adapter);
							}
							Constant.isUploadOfSubscribeMy = true;
						}else{
//							if(header != null)
//							ToastAlone.showToast(getActivity(), header.getMessage(), 1);
							if(!context.getMemeryCache().isExist(key)){
								View view = listview.getEmptyView();
								if(view == null){
									listview.setEmptyView(viewEmpty);
								}
							}	
						}
					}else{
						ToastAlone.showToast(getActivity(), "网络异常，请稍后再试~", 1);
					}
				}
			}

			@Override
			public void onFailure(int code, String message) {
				// TODO Auto-generated method stub
				Logger.i("tag---onFailure", message);
				isAskingServer = false;
				if(refreshListView != null){
					refreshListView.onRefreshComplete();
				}
				
				//判断是否登录，若登录，判断是否有缓存，若有缓存，则显示数据，若无缓存则显示 empty
				//若未登录，显示未登录的数据；
				
					String key = MD5.getMessageDigest(V1VideoHttpApi.GET_THEME_ALL_THEME());
					if(((AppContext) getActivity().getApplicationContext()).getMemeryCache().isExist(key)){
						//若有缓存，则读缓存，显示数据；缓存读取到listVideo
						Logger.i(TAG, "有缓存111111111");
						getDataFromCache(key);
						updata();
						if(adapter != null){
							adapter.updata(listVideo);
							adapter.notifyDataSetChanged();
						}else{
							adapter = new ThemeAllAdapter(getActivity(), listVideo);
							listview.setAdapter(adapter);
						}
					}else{
						Logger.i(TAG, "无缓存11111111");
						View view = listview.getEmptyView();
						if(view == null){
							listview.setEmptyView(viewEmpty);
						}
					}
			}
			
		});
	}
	
	/***
	 * //若本地存在缓存，则判断：若一样，则不做存储，提示 无更新
	 * @param key
	 * @param context
	 * @param header
	 * @return
	 */
	private boolean judgeOldAndrNewData(String key, AppContext context,
			com.v1.video.domain.BaseEntity.Header header) {
		boolean isSame = true;
		if(context.getMemeryCache().isExist(key)){
			Logger.i(TAG, "有缓存2222222222222");
			String value = context.getMemeryCache().get(key);
			
			if(header != null){
				if(!value.equals("") && header.getMarkid() != null && value.equals(header.getMarkid())){
					//两次数据一致，提示没有更新
//					toastNoUpdata();
//						if(adapter == null){
//							getDataFromCache();
//							adapter = new SubscribeSelectionAdapter(getActivity(), listVideo);
//							listview.setAdapter(adapter);
//						}
//						return;
				}else{
					isSame = false;//两次数据不一致，下面拿到数据去存储；
				}
			}
		}else{
			Logger.i(TAG, "无缓存2222222222222");
		}
		return isSame;
	}

	private void setListener() {
		refreshListView.setOnRefreshListener(new OnRefreshListener2() {

			@Override
			public void onPullDownToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				Logger.d(TAG, "下拉刷新");
				
//				if(!LoginInfo.getInstance().isLogin()){
//					layoutNoData.setVisibility(View.VISIBLE);
//					refreshListView.setVisibility(View.GONE);
//					txtToLoginOrSelection.setText(getResources().getString(R.string.tips_title_subscribe_my_no_login));
//					return;
//				}else{
					refreshListView.setVisibility(View.VISIBLE);
					layoutNoData.setVisibility(View.GONE);
					refreshPullDown(true);
//				}
			}

			@Override
			public void onPullUpToRefresh(PullToRefreshBase refreshView) {
				// TODO Auto-generated method stub
				
			}
		
		});
		refreshListView.setOnScrollListener(new OnScrollListener() {

			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
				// TODO Auto-generated method stub
				switch (scrollState) {
				case OnScrollListener.SCROLL_STATE_IDLE:
					ImageLoader.getInstance().resume();
					break;
				case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
					ImageLoader.getInstance().pause();
					break;
				case OnScrollListener.SCROLL_STATE_FLING:
					ImageLoader.getInstance().pause();
					break;
				}
			}

			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				// TODO Auto-generated method stub

			}
		});
		
		viewEmpty.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(!Helper.checkConnection(getActivity())){
					return;
				}
				if(!isAskingServer){
					isAskingServer = true;
					getDataFromServer();
				}
			}
		});
	}
	
	private void getDataFromCache(String key){
		if(listVideo != null){
			listVideo.clear();
		}
		listVideo = Utils.getThemeAllThemeInfoFromFile(getActivity(),key);		
		if(listVideo == null){
			listVideo = new ArrayList<ThemeTB>();
		}
	}
	
	private void saveInfoToFile(List<ThemeTB> listVideo,String key){
		Gson gson = new Gson();
		Utils.saveThemeAllToFile(getActivity(),
				gson.toJson(listVideo),key);
	}
	
	private void toastNoUpdata(){
		layoutNoDataToUpdata.setVisibility(View.VISIBLE);
		AlphaAnimation anim = new AlphaAnimation(1.0f, 0.01f);
		anim.setDuration(4000);
		anim.setAnimationListener(new Animation.AnimationListener() {
            
		    @Override
		    public void onAnimationStart(Animation animation) {    
		    }
		            
		    @Override
		    public void onAnimationRepeat(Animation animation) {    
		    }
		            
		    @Override
		    public void onAnimationEnd(Animation animation) {
		        //渐变动画结束后，执行此方法，跳转到主界面 
		    	layoutNoDataToUpdata.setVisibility(View.GONE);
		    }
		});
		layoutNoDataToUpdata.setAnimation(anim);
		anim.start();
	}
	private void toastUpdata(){
		if(Constant.isUploadOfSubscribeMy){
			layoutHasData.setVisibility(View.VISIBLE);
			AlphaAnimation anim = new AlphaAnimation(1.0f, 0.01f);
			anim.setDuration(4000);
			anim.setAnimationListener(new Animation.AnimationListener() {
	            
			    @Override
			    public void onAnimationStart(Animation animation) {    
			    }
			            
			    @Override
			    public void onAnimationRepeat(Animation animation) {    
			    }
			            
			    @Override
			    public void onAnimationEnd(Animation animation) {
			        //渐变动画结束后，执行此方法，跳转到主界面 
			    	layoutHasData.setVisibility(View.GONE);
			    }
			});
			layoutHasData.setAnimation(anim);
			anim.start();
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		Logger.i(TAG, "onActivityResult执行了111111111111");
		if(LoginInfo.getInstance().isLogin()){
			refreshListView.setVisibility(View.VISIBLE);
			layoutNoData.setVisibility(View.GONE);
			refreshPullDown(false);
		}
	}
}
